﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EntityObjects;
using BAL.Controller;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.Net;

namespace PresentationLayer.View.StoreClerk
{
    public partial class WebForm7 : System.Web.UI.Page
    {
        RaisePurchaseOrderControl control;
        PurchaseOrder po;
        CreatePDF cPDF;
        List<PurchaseOrderDetails> poDLst;
        static int tmp;
        string poNo = "";
        static int count = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            control = new RaisePurchaseOrderControl();
           
            poDLst = new List<PurchaseOrderDetails>();
            po = new PurchaseOrder();
            cPDF = new CreatePDF();
            if (!IsPostBack)
            {
                Session["purchase"] = true;
                poNo = control.getPurchaseOrderNo();
                Panel1.Visible = false;
                tmp = 0;
                populateField("ALPA");
                btnPrintPDF.Enabled = false;
                btnDownloadPDF.Enabled = false;
            }

        }

        protected void Supplier1_Click(object sender, EventArgs e)
        {
            changeStatus(Convert.ToInt16(ViewState["ALPA1"]));
            populateField("ALPA");
            Supplier1.ForeColor = System.Drawing.Color.Magenta;
        }

        private void changeStatus(int i)
        {
            if (i != 1)
            {
                btnOrder.Enabled = true;
                btnPrintPDF.Enabled = false;
                btnDownloadPDF.Enabled = false;               
                lblOrderMes.Text = "Order has not been placed to " + po.SupplierId;
            }
            else
            {
                btnOrder.Enabled = false;
                btnPrintPDF.Enabled = true;
                btnDownloadPDF.Enabled = true;
                lblOrderMes.Visible = true;
                lblOrderMes.Text = "Order has been placed to " + po.SupplierId;
            }
        }

        protected void Supplier2_Click(object sender, EventArgs e)
        {
            changeStatus(Convert.ToInt16(ViewState["BANE1"])) ;           
            populateField("BANE");
            Supplier2.ForeColor = System.Drawing.Color.Magenta;
        }
        protected void Supplier3_Click(object sender, EventArgs e)
        {
            changeStatus(Convert.ToInt16(ViewState["CHEP1"])); 
            populateField("CHEP");
            Supplier3.ForeColor = System.Drawing.Color.Magenta;
        }
        protected void btnOrder_Click(object sender, EventArgs e)
        {
            if (lblWantedDate.Text.ToString().Equals(""))
            {
                errMsg.Text = "Please select the date!";
            }
            else
            {
                po.PONo = lblPO.Text.ToString();
                po.SupplierId = lblSupplier.Text.ToString();
                po.OrderedBy = lblClerk.Text.ToString();          
                po.OrderedOn = Convert.ToDateTime(lblToday.Text);
                po.PoDetails_list = (List<PurchaseOrderDetails>)Session[lblSupplier.Text];
                po.WantedDate = Convert.ToDateTime(lblWantedDate.Text.ToString());
                po.Status = "Purchased";
                control.Insert(po);

                //Create PDF File
                cPDF.Create(po, po.SupplierId);
                ViewState[po.SupplierId + "1"] = 1;
                btnOrder.Enabled = false;
                btnPrintPDF.Enabled = true;
                btnDownloadPDF.Enabled = true;
                lblOrderMes.Visible = true;
                lblOrderMes.Text="Order has been placed to " + po.SupplierId;
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {          
            Server.Transfer("RaisePurchaseOrder.aspx");
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Calendar1.Visible = true;
        }

        protected void Calendar1_SelectionChanged(object sender, EventArgs e)
        {         
            DateTime wantDate = DateTime.Parse(Calendar1.SelectedDate.ToString("yyyy/MM/dd"));
            DateTime todayDate=DateTime.Parse(DateTime.Now.ToString("yyyy/MM/dd"));
            if (DateTime.Compare(wantDate, todayDate) < 0)
            {
                errMsg.Text = "The selected date must not be earlier than today date.";
                errMsg.Visible = true;
            }
            else if (DateTime.Compare(wantDate, todayDate) > 0)
            {
                errMsg.Visible = false;
                string[] str = wantDate.ToString().Split(' ');
                lblWantedDate.Text = str[0];
                Calendar1.Visible = false;
            }
          
        }
        private void populateField(string supName)
        {

            string today = DateTime.Now.ToString("yyyy-MM-dd");
            string[] t1 = today.Split('-');

            List<PurchaseOrderDetails> pDLst = (List<PurchaseOrderDetails>)Session[supName];

            if (pDLst != null)
            {
                Panel1.Visible = true;
                Panel2.Visible = false;

                generatePONO(supName, t1);

                lblPO.Text = (String)ViewState[supName];
                lblToday.Text = today;
                lblSupplier.Text = supName;
                //lblClerk.Text = (String)Session["CurrentUser"];
                double d = 0.0;
                foo.DataSource = pDLst;
                foo.DataBind();

                foreach (GridViewRow gvr in foo.Rows)
                {
                    PurchaseOrderDetails tp = new PurchaseOrderDetails();

                    string ItemId = gvr.Cells[0].Text;
                    int qty = (Convert.ToInt16(gvr.Cells[2].Text));
                    double price = Convert.ToDouble(gvr.Cells[3].Text);

                    tp.ItemId = gvr.Cells[0].Text;
                    tp.OrderQty = (Convert.ToInt16(gvr.Cells[2].Text));
                    tp.Price = Convert.ToDouble(gvr.Cells[3].Text);
                    tp.Amount = (tp.OrderQty * tp.Price);

                    Label l = (Label)gvr.Cells[1].FindControl("Description");
                    Label l1 = (Label)gvr.Cells[4].FindControl("Amount");
                    Label total = (Label)((GridView)foo).FooterRow.FindControl("lblTotal");

                    d += tp.Amount;

                    l.Text = control.getDescription(tp.ItemId);
                    l1.Text = (tp.OrderQty * tp.Price).ToString();
                    total.Text = d.ToString();
                }
                Label1.Text = d.ToString();
            }
            else
            {
                Panel1.Visible = false;
                Panel2.Visible = true;
                //errMsg.Text = "There is no item to show in the Purchase Order File";
            }
        }

        private void generatePONO(string supName, string[] t1)
        {
            if (ViewState[supName] == null)
            {
                if (tmp == 0 && poNo != null && poNo != "") tmp = Convert.ToInt16(poNo.Substring(6));
                if (tmp == 0 && poNo == null && poNo == "") ViewState[supName] = t1[0] + t1[1] + "001";
                    else if (tmp >= 9 && tmp < 100) ViewState[supName] = t1[0] + t1[1] + "0" + ++tmp;
                    else if (tmp < 9) ViewState[supName] = t1[0] + t1[1] + "00" + ++tmp;
                    else ViewState[supName] = t1[0] + t1[1] + ++tmp;              
            }
        }

        protected void btnDownloadPDF_Click(object sender, ImageClickEventArgs e)
        {
            Response.ContentType = "Application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + lblSupplier.Text + ".pdf");
            Response.TransmitFile(Server.MapPath("PDFs/" + lblSupplier.Text + ".pdf"));
            Response.End();
        }

        protected void btnPrintPDF_Click(object sender, ImageClickEventArgs e)
        {    
           Response.Redirect("PDFs/" + lblSupplier.Text + ".pdf");
        }
    }
}